const CACHE_NAME = 'wiki';
const locationUrl = location.origin + location.pathname.replace('serviceWorker.js', '');
let cdn = "https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-y/";
let version = '6';

const cdnCache = [
	cdn + "marked/0.3.19/marked.min.js",
	cdn + "jquery/3.6.0/jquery.min.js",
	cdn + "mathjax/2.7.9/MathJax.js?config=TeX-AMS_CHTML",
	cdn + "mathjax/2.7.9/config/TeX-AMS_CHTML.js?V=2.7.9",
	cdn + "mathjax/2.7.9/jax/output/CommonHTML/jax.js?V=2.7.9",
	cdn + "mathjax/2.7.9/jax/output/CommonHTML/fonts/TeX/fontdata.js?V=2.7.9",
	cdn + "mathjax/2.7.9/jax/output/CommonHTML/fonts/TeX/AMS-Regular.js?V=2.7.9",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/woff/MathJax_Caligraphic-Regular.woff",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/woff/MathJax_Math-Italic.woff",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/otf/MathJax_Caligraphic-Regular.otf",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/otf/MathJax_Math-Italic.otf",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/woff/MathJax_Main-Regular.woff",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/woff/MathJax_Size1-Regular.woff",
	cdn + "mathjax/2.7.9/fonts/HTML-CSS/TeX/woff/MathJax_Size2-Regular.woff",
];

const urlsToCache = [
	locationUrl,
	locationUrl + 'index.html',
];

// 白名单
const CACHE_LIST = [
	'lf3-cdn-tos.bytecdntp.com',
	location.host,
];

const fetchAfterCache = function(eventRequest) {
	return fetch(eventRequest, {
		cache: 'no-cache',
	}).then(function(responseFetch) {
		if (!responseFetch.ok) {
			return responseFetch;
		}
		// 成功后复制一遍再缓存
		let responseFetchToCache = responseFetch.clone();
		caches.open(CACHE_NAME).then(function(cache) {
			return cache.delete(eventRequest, {
				ignoreSearch: true,
			}).then(() => {
				return cache.put(eventRequest, responseFetchToCache);
			});
		});
		return responseFetch;
	});
};

self.addEventListener('install', event => {
	self.skipWaiting();
	// 缓存cdn
	event.waitUntil(
		caches.open('cdn').then(cache => {
			return Promise.all([
				cache.addAll(cdnCache),
				fetchAfterCache(new Request(locationUrl)),
				fetchAfterCache(new Request(locationUrl + 'index.html'))
			]);
		})
	);
});

self.addEventListener("activate", event => {
	event.waitUntil(
		caches.keys().then(keys => {
			// 删除旧缓存
			Promise.all(
				keys.map(key => {
					if (CACHE_NAME === key) {
						return caches.delete(key);
					}
				})
			);
		})
	);
});

self.addEventListener('fetch', function(event) {
	let eventRequest = event.request;
	let requestURL = eventRequest.url;
	let objectURL = new URL(requestURL);
	let indexDate = requestURL.indexOf('?file=');
	let monthT = requestURL.indexOf('?t=');
	// 首页带地址参数去参数，并过滤缓存请求的日期参数
	if (indexDate !== -1 && monthT === -1) {
		objectURL.protocol = self.location.protocol;
		objectURL.search = '?t=' + Math.ceil(new Date().getDate() / 7);
		eventRequest = new Request(objectURL.href);
	}
	// 过滤 已知其他跨域的
	let skipWorker = CACHE_LIST.indexOf(new URL(requestURL).host);
	if (skipWorker > -1) {
		event.respondWith(
			caches.match(eventRequest).then((response) => {
				if (response) {
					return response;
				}
				// 没缓存网络获取再缓存
				return fetchAfterCache(eventRequest).catch(() => {
					if (response) {
						return response;
					}
				});
			})
		);
	}
});

self.addEventListener('error', event => {
	console.log(event);
});
